<?php
// This controller handles the logic for the my admin page

class AdminController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	/**
	 * Description: This method renders the supplier admin page if the guest is logged in and is a supplier. If the user is not a supplier
	 * then the user will not be given access to the page. If the viewer is not logged in, then the application will redirect the view
	 * to the login page.
	 * Returns: Nothing
	 */
	public function actionSupplier()
	{
		if(Yii::app()->user->isGuest)
		{
			echo "Please Login first. We will redirect you to the login page in 3 secs";
			header("refresh:3;url=".Yii::app()->request->baseUrl);
		}
		else if(Yii::app()->user->userType=='b')
		{
			echo "you have no authority to view the supplier page";
		}
		else
		{
			$model=new Users;
			$org_model=new Organizations;
			$bank_model=new BankAccounts;
			$model->scenario='update';
			$org_model->scenario='update';
			$bank_model->scenario='update';
			$usersDataProvider = new CActiveDataProvider('Users', array(
								'criteria'=>array(
										'condition'=>'organization_ID='.Users::model()->findByPk(Yii::app()->user->userID)->organization_ID.
														' and user_ID!='.Yii::app()->user->userID.' and active=1',
									),
								'pagination'=>array(
										'pageSize'=>20,
									),
							/*	'sort'=>array(
										'defaultOrder'=>'delivered_price_per_gallon ASC',
									),*/
								)
							);
			$this->render('supplier', array('model'=>$model, 'org_model'=>$org_model, 'bank_model'=>$bank_model, 'usersDataProvider'=>$usersDataProvider));
		}
	}
	
	/**
	 * Description: This method renders the buyer admin page if the guest is logged in and is a buyer. If the user is not a buyer
	 * then the user will not be given access to the page. If the viewer is not logged in, then the application will redirect the view
	 * to the login page.
	 * Returns: Nothing
	 */	
	public function actionBuyer()
	{
		if(Yii::app()->user->isGuest)
		{
			echo "Please Login first. We will redirect you to the login page in 3 secs";
			header("refresh:3;url=".Yii::app()->request->baseUrl);
		}
		else if(Yii::app()->user->userType=='s')
		{
			echo "you have no authority to view the buyer page";
		}
		else
		{
			$model=new Users;
			$org_model=new Organizations;
			$bank_model=new BankAccounts;
			$model->scenario='update';
			$org_model->scenario='update';
			$bank_model->scenario='update';
			$usersDataProvider = new CActiveDataProvider('Users', array(
							//	'keyAttribute'=>'user_ID user_name',
								'criteria'=>array(
										'condition'=>'organization_ID='.Users::model()->findByPk(Yii::app()->user->userID)->organization_ID.
														' and user_ID!='.Yii::app()->user->userID.' and active=1',
									),
								'pagination'=>array(
										'pageSize'=>20,
									),
							/*	'sort'=>array(
										'defaultOrder'=>'delivered_price_per_gallon ASC',
									),*/
								)
							);
			$this->render('buyer', array('model'=>$model, 'org_model'=>$org_model, 'bank_model'=>$bank_model, 'usersDataProvider'=>$usersDataProvider));
		}
	}
	
	/**
	 * Description: This method makes an ajax call to update the organization information of the current user in the database
	 * Returns: 'org-success' if true, String of errors if false
	 */
	public function actionOrganization()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$org_model=new Organizations;
			$org_model->scenario='update';
			
			$org_model->organization_ID=$_POST['Organizations']['organization_ID'];
			$org_model->organization_name=$_POST['Organizations']['organization_name'];
			$org_model->DBA=$_POST['Organizations']['DBA'];
			$org_model->fed_ID=$_POST['Organizations']['fed_ID'];
			$org_model->address1=$_POST['Organizations']['address1'];
			$org_model->state=$_POST['Organizations']['state'];
			$org_model->city=$_POST['Organizations']['city'];
			$org_model->zip=$_POST['Organizations']['zip'];
			$org_model->contact_first_name=$_POST['Organizations']['contact_first_name'];
			$org_model->contact_last_name=$_POST['Organizations']['contact_last_name'];
			$org_model->phone_number=$_POST['Organizations']['phone_number'];
			$org_model->email_address=$_POST['Organizations']['email_address'];
			$org_model->organization_type_ID=$_POST['Organizations']['organization_type_ID'];
			if($org_model->validate())
			{
				$org_model->updateByPk($org_model->organization_ID, $_POST['Organizations']);
				echo CJSON::encode('org-success');
			}
			else
			{
				echo CJSON::encode($org_model->errors);
			}
		}
	}
	
	/**
	 * Description: This method makes an ajax call to update the profile information of the current user in the database
	 * Returns: 'profile-success' if true, String of errors if false
	 */
	public function actionProfile()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$attributes=array();
			$attributes['contact_first_name']=$_POST['Users']['contact_first_name'];
			$attributes['contact_last_name']=$_POST['Users']['contact_last_name'];
			$attributes['address1']=$_POST['Users']['address1'];
			$attributes['state']=$_POST['Users']['state'];
			$attributes['city']=$_POST['Users']['city'];
			$attributes['zip']=$_POST['Users']['zip'];
			$attributes['phoneNumber']=$_POST['Users']['phoneNumber'];
			$attributes['emailAddress']=$_POST['Users']['emailAddress'];

			$model=new Users;
			$model->scenario='update';
			$model->user_name=$_POST['Users']['user_name'];
			$model->user_ID=Yii::app()->user->userID;
			
			//if password field has input, verify the input and update
			//that password in database if it's valid
			if($_POST['Users']['password']!=null)
			{
				$attributes['password']=$_POST['Users']['password'];
				$model->password=$_POST['Users']['password'];
			}
			if($_POST['Users']['password2']!=null)
				$model->password2=$_POST['Users']['password2'];
			$model->attributes=$attributes;
			if($model->validate())
			{
				$model->updateByPk($model->user_ID, $attributes);
				Yii::app()->user->name=$model->user_name;
				echo CJSON::encode('profile-success');
			}
			else
			{
				echo CJSON::encode($model->errors);
			}
		}
	}
	
	/**
	 * Description: This method makes an ajax call to update the payment information of the current user in the database
	 * Returns: 'payment-success' if true, String of errors if false
	 */
	public function actionPayment()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$bank_model=new BankAccounts;
			$bank_model->scenario='update';
			
			$result = BankAccounts::model()->getAccount(Yii::app()->user->userID);
			
			foreach ($result as $row) {
				$accountID = $row['account_ID'];
			}
			
			$attributes = array();
			
			$bank_model->account_ID=$accountID;
			$attributes['bank_name']=$_POST['BankAccounts']['bank_name'];
			$attributes['branch_name']=$_POST['BankAccounts']['branch_name'];
			$attributes['city']=$_POST['BankAccounts']['city'];
			$attributes['state']=$_POST['BankAccounts']['state'];
			$attributes['zip']=$_POST['BankAccounts']['zip'];
			
			if (is_numeric($_POST['BankAccounts']['routing_number']))
				$attributes['routing_number']=$_POST['BankAccounts']['routing_number'];
			
			if (is_numeric($_POST['BankAccounts']['account_number'])) {
				$attributes['account_number']=$_POST['BankAccounts']['account_number'];
				$attributes['four_digit_account_number']=substr($attributes['account_number'], -4);
			}
			
			$bank_model->attributes = $attributes;
			
			if($bank_model->validate())
			{
				$bank_model->updateByPk($bank_model->account_ID, $attributes);
				echo CJSON::encode('bank-success');
			}
			else
			{
				echo CJSON::encode($bank_model->errors);
			}
		}
	}
	
	/**
	 * Description: This method makes an ajax call to update the rack information of a supplier
	 * Returns: 'rack-success' if true, 'rack-error' if false
	 */
	public function actionRacks()
	{
		if(Yii::app()->request->isAjaxRequest && isset($_POST['racks']))
		{
			$rack_model=new OrgRackRelation;
			$rack_model->scenario='update';
			
			$organizationID = Users::model()->getOrganizationID(Yii::app()->user->userID);
			
			$rack_model->deleteAllByAttributes(array('organization_ID'=>$organizationID));
			
			$racks = $_POST['racks'];
			
			foreach ($racks as $rack) {
				$rack_model->setIsNewRecord(true);
				$rack_model->organization_ID = $organizationID;
				$rack_model->rack_ID = Racks::model()->getRackIDByName($rack);
				
				$rack_model->save();
			}
			
			echo CJSON::encode('rack-success');
		}
		else
			echo CJSON::encode('rack-error');
	}
	
	/**
	 * Description: This method makes an ajax call to add a new user
	 * Returns: 'adduser-success' if true, String of errors if false
	 */
	public function actionAddUser()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$prefix='adduser_';
			$model=new Users;
			$model->scenario='register';
			$model->contact_first_name=$_POST[$prefix.'contact_first_name'];
			$model->contact_last_name=$_POST[$prefix.'contact_last_name'];
			$model->phoneNumber=$_POST[$prefix.'phoneNumber'];
			$model->emailAddress=$_POST[$prefix.'emailAddress'];
			$model->user_name=$_POST[$prefix.'user_name'];
			$model->user_role_type_ID=$_POST[$prefix.'user_role_type_ID'];
			$model->password=$_POST[$prefix.'password'];
			$model->password2=$_POST[$prefix.'password2'];
			
			$user=Users::model()->with('organization')->findByPk(Yii::app()->user->userID);
			$model->address1=$user->organization->address1;
			$model->address2=$user->organization->address2;
			$model->city=$user->organization->city;
			$model->state=$user->organization->state;
			$model->zip=$user->organization->zip;
			$model->organization_ID=$user->organization_ID;
			$model->user_type_ID=$user->user_type_ID;
			$model->active=1;
			if($model->save())
			{
				echo CJSON::encode('adduser-success');
			}
			else
			{
				echo CJSON::encode($model->errors);
			}
		}
	}
	
	/**
	 * Description: This method makes an ajax call to check if the new username request is valid
	 * Returns: Nothing if true, String error message if false
	 */
	public function actionCheckValid()
	{	
		if(Yii::app()->request->isAjaxRequest)
		{
			$model=new Users;
			$model->scenario='update';
			$model->user_name=$_POST['Users']['user_name'];
			$model->user_ID=Yii::app()->user->userID;
			if(!$model->validate(array('user_name', 'user_ID')))
				echo "User Name \"".$_POST['Users']['user_name']."\" has already been taken";
		}
	}
	
	/**
	 * Description: This method makes an ajax call to check if the new organization name request is valid
	 * Returns: Nothing if true, String error message if false
	 */
	public function actionCheckOrgValid()
	{	
		if(Yii::app()->request->isAjaxRequest)
		{
			$model=new Organizations;
			$model->scenario='update';
			$model->organization_name=$_POST['Organizations']['organization_name'];
			$model->organization_ID=$_POST['Organizations']['organization_ID'];
			if(!$model->validate(array('organization_name', 'organization_ID')))
				echo "Organization Name \"".$_POST['Organizations']['organization_name']."\" has already been taken";
		}
	}
	
	/**
	 * Description: This method makes an ajax call to retrieve the user information when editing a user
	 * Returns: The user record
	 */
	public function actionEditUser()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$user_ID=$_POST['userID'];
			$record=Users::model()->findByPk($user_ID);
			echo CJSON::encode($record);
		}
	}
	
	/**
	 * Description: This method makes an ajax call to set the requested user's active field to 0 'removing' them from the active users list
	 * Returns: 'delete-success' if true, userID if false
	 * Note: need to forbid the deleted logged in users to continue, manipulating persistent data
	 */
	public function actionDeleteUser()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$user_ID=$_POST['userID'];
			$recordNum=Users::model()->updateByPk($user_ID, array('active'=>'0'));
			if($recordNum==1)
			{
				echo CJSON::encode('delete-success');
			}
			else
			{
				echo CJSON::encode($user_ID);
			}
		}
	}
	
	/**
	 * Description: This method makes an ajax call to update a user's info
	 * Returns: 'update-success' if true, String of errors if false
	 */
	public function actionUpdate()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$attributes=array();
			$attributes['contact_first_name']=$_POST['contact_first_name'];
			$attributes['contact_last_name']=$_POST['contact_last_name'];
			$attributes['phoneNumber']=$_POST['phoneNumber'];
			$attributes['emailAddress']=$_POST['emailAddress'];
			$attributes['user_name']=$_POST['user_name'];
			$attributes['user_role_type_ID']=$_POST['user_role_type_ID'];
			
			$model=new Users;
			$model->scenario='edit';
			$model->user_ID=$_POST['user_ID'];

			if($_POST['password']!=null)
			{
				$attributes['password']=$_POST['password'];
				$model->password=$_POST['Users']['password'];
			}
			if($_POST['password2']!=null)
				$model->password2=$_POST['password2'];
			$model->attributes=$attributes;
			if($model->validate())
			{
				$model->updateByPk($_POST['user_ID'], $attributes);
				Yii::app()->user->name=$model->user_name;
				echo CJSON::encode('update-success');
			}
			else
			{
				echo CJSON::encode($model->errors);
			}
		}
	}
}
?>
